<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {
	/**
	 * @var string the default layout for the controller view. Defaults to '//layouts/column1',
	 * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $metaKeywords='';
	public $metaDescription='';
	public $layout = '//layouts/main'; 
	public $logged = 0; //此次请求是否已经做日志记录,0为未做
	public $userType = 2; //用户类型，1表示为后台用户，2表示前台用户，0表示未知
	public $opflag = false; //此次请求的数据库操作结果,false 代表失败 true代表成功
	public $limit=100;//毫秒
	public $execSqlFail = false;  //在此次请求的控制器执行期间内，有无sql执行失败
	public static $postLimitKey = 'post_limit_repeat';

	/** 
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $menu = array ();
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs = array ();

    public function init() {
        parent::init();
    }

    protected function beforeAction($action)
    {   
		parent::beforeAction($action);
        //防止表单重复提交
		if(Yii::app()->request->getIsPostRequest()){
            //列外路由
			$excludeRoutes = array('wap/index/loginpost','wap/index/regpost','sms/send/index','user/login/post','user/login/postmerchant','user/register/post','user/register/postmerchant','admin/category/categorydropdownlist','admin/attachment/upload','www/attachment/upload','www/category/categorydropdownlist','admin/permission/postchildrenrole','admin/permission/postchildrentask','admin/areacontact/index');
			$r = strtolower($this->getRoute());
			
			if(!in_array($r,$excludeRoutes)){
				$uri = Yii::app()->request->requestUri;
                $md5Result = md5(serialize($_POST).$uri);
				$lastMd5Result = '';
				if($this->userType == 1){
                    $lastMd5Result = Yii::app()->admin->getState(self::$postLimitKey,'');
				}
				elseif($this->userType == 2){
                    $lastMd5Result = Yii::app()->frontuser->getState(self::$postLimitKey,'');
				}

				if($md5Result == $lastMd5Result){
					if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest'){
						//AJAX提交，返回JSON格式
						echo UtilD::handleResult(0,'请勿重复提交,或者您的内容没有修改!');
					}else{
                    	$refurl = Yii::app()->request->getUrlReferrer()?Yii::app()->request->getUrlReferrer():'http://'.$_SERVER['HTTP_HOST'];
						echo "<script>alert('请勿重复提交,或者您的内容没有修改');window.location='{$refurl}';</script>";
					}
					Yii::app()->end();
				}
				else{
				    if($this->userType == 1){
                        Yii::app()->admin->setState(self::$postLimitKey,$md5Result);
				    }
				    elseif($this->userType == 2){
                        Yii::app()->frontuser->setState(self::$postLimitKey,$md5Result);
				    }
				}
			}
		}

        return true;
    }

	/**
	 * 这是一个过滤器，负责过滤所有request对象里面的sql注入，方法原生态保留request值大小写，
	 **/
	public function filterRequestI($filterChain) {
		if (count ( $_GET )) {
			 UtilD::enSlashesAll($_GET);
		}
		if (count ( $_POST )) {
			UtilD::enSlashesAll($_POST);
		}
		if (count ( $_COOKIE )) {
			UtilD::enSlashesAll($_COOKIE);
		}
		$filterChain->run();
	}
	public function getRouteI(){
		$route=$this->getRoute();
		$actions=$this->actionParams;
		if(!isset($actions['r'])){
			$actions['r']=Yii::app ()->defaultController;
		}elseif(empty($actions['r'])){
			$actions['r']=Yii::app ()->defaultController;
		}
		if(strlen($actions['r'])<$route){
			$actions['r']=$this->getModule()->defaultController;
		}
		if($route===$this->getUniqueId()){
			if(strlen($actions['r'])>strlen($route)){
				return $actions['r'];
			}else{
				return $route.='/'.$this->defaultAction;
			}
		}else{
			return $route;
		}

	}
	public function filterRequestLimit($filterChain) {
		$secs = (string)$this->limit;
		$secs = bcdiv($secs,'1000',4);
		$session = Yii::app()->session;
		$session->open();
		$lastUpdate=$session['lastUpdate'];
		$currentTime = (string)microtime(true);
		$session['lastUpdate']=$currentTime ;
		if ($lastUpdate) {
			$tmp=bcadd($lastUpdate,$secs,4);
			if(bccomp($tmp,$currentTime)!==-1){
				$callback = Yii::app()->request->getParam('callback',false);
				if($callback===false){
					throw new CHttpException ( 404, '操作过频繁！' );
				}else{
					$res = UtilD::handleResult ( 2, '操作过频繁！'  );
					echo $callback."(".$res.")";
					exit;

				}
			}
		}
		if($filterChain instanceof CFilterChain){
			$filterChain->run();
		}

	}
//    
//    public function filters() {
//		return array (
//			'RequestI',
//		); 
//	}
//	
	/**
	 * 显示子视图
	 * @param string $widget
	 * @param string $style
	 */
	public function display( $data,$widget, $style = 'default') {
		$viewPath = Yii::app ()->basePath . DIRECTORY_SEPARATOR . 'widgets' . DIRECTORY_SEPARATOR . $widget . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $style . '.php';
        if (file_exists ( $viewPath )) {
			include ($viewPath);
		}else{
			throw new CHttpException ( 404, '不存在名字为['.$widget . '/' . $style .']的web组建！' );
		}
	}
}
